package top.lucky.redishmdp.service.impl;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.lucky.redishmdp.dto.Result;
import top.lucky.redishmdp.entity.Shop;
import top.lucky.redishmdp.mapper.ShopMapper;
import top.lucky.redishmdp.service.ShopService;
import top.lucky.redishmdp.utils.RedisConstants;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static top.lucky.redishmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static top.lucky.redishmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * @author Jane
 * @date 2022/5/24, 10:40
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //Shop shop = queryShopPassThrough(id);

        //互斥锁解决缓存击穿
        Shop shop = queryShopMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        //返回
        return Result.ok(shop);
    }

    /**
     * 互斥锁解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryShopMutex(Long id) {
        //从redis查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String lock = RedisConstants.LOCK_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在 存在:返回 不存在,根据id查询数据库
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            //返回错误信息
            return null;
        }
        //实现缓存重建
        Shop shop = null;

        try {
            //获取互斥锁
            Boolean isLock = lock(lock);

            //判断是否获取成功
            if (!isLock) {
                //失败，休眠并重试
                Thread.sleep(50);
               return queryShopPassThrough(id);
            }
            //成功。根据id查询
            shop = getById(id);

            //模拟重建延迟
            Thread.sleep(200);
            //数据库不存在,返回错误  存在:写入redis
            if (shop == null) {
                //写入空值
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            //释放互斥锁
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(key);
        }

        return shop;
    }

    /**
     * 缓存穿透
     * @param id
     * @return
     */
    public Shop queryShopPassThrough(Long id) {
        //从redis查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在 存在:返回 不存在,根据id查询数据库
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            //返回错误信息
            return null;
        }
        Shop shop = getById(id);
        //数据库不存在,返回错误  存在:写入redis
        if (shop == null) {
            //写入空值
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }
    public Boolean lock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag);
    }

    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
